<template>
  <div>
    <el-input disabled :value="$route.query.roleName"></el-input>
    <el-tree :props="defaultProps" style="margin: 20px 0" ref="treeRef" node-key="id" :data="allPermissions" show-checkbox
      default-expand-all />
    <el-button :loading="loading" type="primary" @click="save">保存</el-button>
    <el-button @click="cancel">取消</el-button>
    <!-- <el-button @click="$router.go(-1)">取消</el-button> -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleId: '',
      allPermissions: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      loading: false
    }
  },
  methods: {
    // 获取页面数据
    async getPermissions() {
      let roleId = this.roleId
      try {
        let result = await this.$API.permission.toAssign(roleId)
        console.log(result)
        this.allPermissions = result.data.children
        const checkedIds = this.getCheckedIds(this.allPermissions)
        // console.log('------------------------------')
        // console.log(checkedIds)
        this.$refs.treeRef.setCheckedKeys(checkedIds)
      } catch (error) {
        console.log(error)
      }
    },

    // 获取指定角色的权限列表
    getCheckedIds(auths, initArr = []) {
      auths.forEach(item => {
        if (item.select && item.level === 4) {
          initArr.push(item.id)
        } else if (item.children) {
          this.getCheckedIds(item.children, initArr)
        }
      })
      return initArr
    },


    // 保存权限列表
    async save() {
      const checkedIds = this.$refs.treeRef.getCheckedKeys()
      const halfCheckedIds = this.$refs.treeRef.getHalfCheckedKeys()
      var ids = checkedIds.concat(halfCheckedIds).join(",")
      this.loading = true
      await this.$API.permission.doAssign(this.$route.query.id, ids)
      this.loading = false
      this.$message({
        type: 'success',
        message: '分配权限成功'
      });
      this.$router.replace('/acl/role/list')
      // this.$router.go(-1)
      
    },

    // 取消
    cancel() {
      this.$router.replace('/acl/role/list')
    }
  },
  mounted() {
    console.log(this.$route.query)
    this.roleId = this.$route.query.id
    this.getPermissions()
  }
}
</script>

<style scoped></style>
